<template>
  <div>
    <!-- 表单 -->
    <div class="from_post el_radio_let">
      <el-form label-width="180px" :model="fromData" :rules="rules" ref="ruleForm">
        <el-form-item label="书单名称" prop="type_name">
          <el-input v-model="fromData.type_name" placeholder="请输入书单名称"></el-input>
        </el-form-item>
        <el-form-item label="书籍获取方式" prop="way">
          <!-- <el-select v-model="fromData.way" @change="wayChange">
            <el-option value="1" label="筛选书籍"></el-option>
            <el-option value="2" label="选择书单"></el-option>
            <el-option value="3" label="选择书商"></el-option>
            <el-option value="4" label="每日荐书"></el-option>
            <el-option value="5" label="自定义封面及选择书籍"></el-option>
          </el-select> -->

          <el-radio-group v-model="fromData.way" @change="wayChange">
            <div class="wrap">
              <el-radio :label="1">筛选书籍</el-radio>
              <el-radio :label="2">选择书单</el-radio>
              <el-radio :label="3">选择书商</el-radio>
              <el-radio :label="4">每日荐书</el-radio>
              <el-radio :label="5">自定义封面及选择书籍</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="书单封面" class="requ" v-if="fromData.way==5">
          <div class="imgpost">
            <el-upload class="avatar-uploader" name="production" ref="upload" :action="$upUrl" :show-file-list="false" :auto-upload="false" :before-upload="beforeAvatarUpload" :on-change="changimg" accept=".jpg,.png,.jpeg">
              <div class="upimg" style="height:100px;width:100px" v-if="imageUrl" @click.stop="">
                <img :src="imageUrl" class="avatar" />
                <div>
                  <div>
                    <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview(imageUrl)"></i>
                  </div>
                  <div>
                    <i class="el-icon-delete" @click.stop="handleRemove"></i>
                  </div>
                </div>
              </div>
              <div v-else style="height:100px;width:100px" class="upback">
                <div>
                  <i class="el-icon-plus elimg_icon"></i>
                  <div class="elimg_text">添加封面</div>
                </div>
              </div>
            </el-upload>
            <div class="img_ps">
              支持jpg、jpeg、png图片，大小请控制在2M以内。
            </div>
          </div>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="imageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input-number v-model="fromData.sort" type="number" style="min-width: 216px" placeholder="请输入顺序"></el-input-number>
        </el-form-item>
        <el-form-item label="资源商" prop="resource_business_id" v-if="fromData.way==3">
          <el-select v-model="fromData.resource_business_id" @change="getResourceType" placeholder="请选择资源商">
            <el-option v-for="item in resourceOptions" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源商类型" prop="resource_business_type_id" v-if="fromData.way==3">
          <el-select v-model="fromData.resource_business_type_id" placeholder="请选择资源商类型">
            <el-option v-for="item in resourceTypeOptions" :label="item.type_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择主题书单" v-if="fromData.way==2">
          <el-select v-model="fromData.reading_id">
            <el-option v-for="item in themeBookListFilterList" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择荐书书单" v-if="fromData.way==4">
          <el-select v-model="fromData.read_id">
            <el-option v-for="item in everyRecommandBookListFilterList" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="展示模板" prop="template" v-if="[1,3].includes(fromData.way)">
          <el-select v-model="fromData.template" placeholder="请选择展示模板">
            <el-option v-for="item in 7" :label="`模板${item}`" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="[1,3].includes(fromData.way)">
          <div class="templates">
            <img class="template1" v-if="fromData.template==1" src="@/assets/templates/template1.png" alt="">
            <img class="template2" v-if="fromData.template==2" src="@/assets/templates/template2.png" alt="">
            <img class="template3" v-if="fromData.template==3" src="@/assets/templates/template3.png" alt="">
            <img class="template4" v-if="fromData.template==4" src="@/assets/templates/template4.png" alt="">
            <img class="template5" v-if="fromData.template==5" src="@/assets/templates/template5.png" alt="">
            <img class="template6" v-if="fromData.template==6" src="@/assets/templates/template6.png" alt="">
            <img class="template7" v-if="fromData.template==7" src="@/assets/templates/template7.png" alt="">
          </div>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="fromData.intro" type="textarea" placeholder="请输入简介" :rows="5"></el-input>
        </el-form-item>
        <el-form-item>
          <div style="padding: 48px 0 48px 0" class="btn_el">
            <el-button @click="submitForm('ruleForm')" class="btn_establish">
              提交
            </el-button>
            <el-button class="btn_cancel" @click="can">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <x-cropperFixed ref="iscropper" :uploadImg="uploadImgs" @cropPicture="cropPicture" :cropImg="cropImgOne"></x-cropperFixed>

  </div>

</template>

<script>
import vmEditor from "@/components/editor/editor.vue";
import { watch } from "vue";
export default {
  components: {
    vmEditor,
  },
  props: {
    type: { type: String, default: "add" },
    fromData: {
      type: Object,
      default() {
        return {};
      },
    },
    cropImgOne: {
      type: String,
      default: 'true',
    },
    cropImg: {
      type: String,
      default: 'true',
    },
  },
  data() {
    return {
      unimgurl: "",
      imageUrl: "",
      dialogVisible: false,
      uploadImgs: "",
      levelList: [],
      resourceOptions: [],
      resourceTypeOptions: [],
      // 每日荐书列表
      everyRecommandBookListFilterList: [],
      themeBookListFilterList: [],
      // 
      c: [],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: 'blur' }],
        resource_business_id: [{ required: true, message: "请选择资源商", trigger: 'blur' }]
      },
    };
  },
  computed: {},

  activated() {
  },
  watch: {
    fromData: {
      // 修改时部分数据回溯
      handler(val, oldVal) {
        // 监听外部的图片是否请求完毕
        if (val.img != oldVal.img) {
          this.imageUrl = this.$img(this.fromData.img);
          this.wayChange(this.fromData.way)
          if(this.fromData.resource_business_type_id){
            this.getResourceType()
          }
        }
      },

      deep: true, //true 深度监听

    },
  },
  mounted() { },
  methods: {
    wayChange(val) {
      if (val == 2 && !this.themeBookListFilterList?.length) {
        this.getThemeBookList()
      } else if (val == 3 && !this.resourceOptions?.length) {
        this.getResourceOptions()
      } else if (val == 4 && !this.everyRecommandBookListFilterList?.length) {
        this.getEveryRecommandBookList()
      }
    },
    // 每日荐书
    getEveryRecommandBookList() {
      this.request({ url: 'admin/resourceReadRecom/filterList' }).then(res => {
        this.everyRecommandBookListFilterList = res.content
      }).catch(e => this.errorHandler(e))
    },
    // 主题书单
    getThemeBookList() {
      this.request({ url: 'admin/resourceReadingList/filterList' }).then(res => {
        this.themeBookListFilterList = res.content
      }).catch(e => this.errorHandler(e))
    },
    getJumpLists(shop_id, canChanghe = true, lnk) {
      console.log(this.fromData.skip_way, shop_id)
      if (this.fromData.skip_way != 2 || !shop_id) return
      if (canChanghe) this.fromData.link = ''

      this.request({
        url: '/admin/bookHomeBannerShop/getBannerTypeData',
        method: 'get',
        data: {
          shop_id: shop_id
        }
      }).then(res => {
        this.JumpList = res.content
        console.log(this.JumpList);
      }).catch(e => {
        this.JumpList = []
      })
    },
    getResourceType() {
      this.fromData.resource_business_type_id = ''
      this.request({
        url: 'admin/resourceBusinessName/getResourceTypeFilterListByBusinessNameId', data: {
          resource_business_id: this.fromData.resource_business_id
        }
      }).then(res => {
        this.resourceTypeOptions = res.content

      }).catch(e => this.errorHandler(e))
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.fromData.way == 5 && !this.unimgurl) {
            this.$message.warning("请上传书单封面");
            return
          }
          this.fromData.img = await this.uploadImg(this.unimgurl)
          this.$emit("btn_submit", this.fromData);
        }
      });
    },
    // 获取上级列表

    //返回上一页
    can() {
      if (this.$route.query.action) {
        this.$delete(this.$route.query, "action");
      }
      this.pageTurnParams("columnBookList", { action: "refresh" });
    },
    handleRemove() {
      (this.imageUrl = ""), (this.unimgurl = "");
    },
    //选择图片查看详情
    handlePictureCardPreview(img) {
      this.imageUrl = img;
      this.dialogVisible = true;
    },
    // 上传图片
    uploadImg(fileUrl, param) {
      return new Promise(async (reslove) => {
        try {
          if (fileUrl) {
            let imgRes = await this.request({
              url: "/uploads/files",
              method: "post",
              dataType: "blob",
              loading: true,
              data: {
                img: fileUrl,
              },
            });
            if (imgRes) {
              reslove(imgRes.content.img);
            }
          } else {
            reslove(this.fromData.img);
          }
        } catch (err) {
          this.errorHandler(err);
        }
      });
    },

    // 裁剪返回参数
    cropPicture(imgUrl) {
      this.unimgurl = imgUrl.file;
      this.imageUrl = imgUrl.dataURL;
    },
    // 上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpg" || "image/png" || "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 <= 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、png、jpeg 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 图片处理
    changimg(file) {
      const isLt2M = file.size / 1024 / 1024 <= 1;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      } else {
        let that = this;
        const fr = new FileReader();
        fr.readAsDataURL(file.raw);
        fr.onload = function () {
          // console.log(fr.result);
          return (that.uploadImgs = fr.result);
        };
        setTimeout(() => {
          this.$refs.iscropper.showModal({
            cutWidth: 245, // 默认生成截图框宽度
            cutHeight: 245, // 默认生成截图框高度
            rate: "1",
            file: file.raw,
          });
        }, 100);
      }
    },
    getResourceOptions() {
      this.request({ url: '/admin/resourceBusinessName/filterList' }).then(res => {
        this.resourceOptions = res.content
      }).catch(e => this.errorHandler(e))
    }
  },
  created() {
  }
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>
<style lang="scss">
</style>
